﻿using SmartParking.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace SmartParking.Manager
{
    public class ParkingManager : DomainService
    {
        private readonly IRepository<Car> _carRepository;
        private readonly IGuidGenerator _guidGenerator;
        private readonly IRepository<PricingPlan> _planRepository;
        private readonly IRepository<ParkingRecord> _recordRepository;
        public ParkingManager(IRepository<Car> carRepository, IGuidGenerator guidGenerator, IRepository<PricingPlan> planRepository, IRepository<ParkingRecord> recordRepository)
        {
            _carRepository = carRepository;
            _guidGenerator = guidGenerator;
            _planRepository = planRepository;
            _recordRepository = recordRepository;
        }
        public async Task<ParkingRecord> Entry(string lpn)
        {
            var query = await _carRepository.GetQueryableAsync();
            var car = query.Where(c => c.LicensePlateNumber == lpn).FirstOrDefault();
            if (car == null)
            {
                car = new Car(_guidGenerator.Create())
                {
                    LicensePlateNumber = lpn,
                };
                car = await _carRepository.InsertAsync(car);
            }
            var planQuery = await _planRepository.GetQueryableAsync();
            var plan = planQuery.Where(p => p.StartDate <= DateTime.Now && p.EndDate > DateTime.Now).FirstOrDefault();
            if (plan == null)
            {
                throw new UserFriendlyException("There is no plan contains current moment");
            }
            else
            {
                var record = new ParkingRecord(_guidGenerator.Create())
                {
                    Car = car,
                    Plan = plan,
                };
                record = await _recordRepository.InsertAsync(record);
                return record;
            }
        }
        public async Task<TimeSpan> GetParkingTimeAsync(string lpn)
        {
            var query = await _recordRepository.GetQueryableAsync();
            var record = query.Where(r => r.Car.LicensePlateNumber == lpn).OrderByDescending(r => r.CreationTime).FirstOrDefault();
            var diff = (record.LeaveTime ?? DateTime.Now) - record.CreationTime;
            return diff;
        }
    }
}
